﻿#include "addjsontools.h"

AddJsonTools::AddJsonTools()
{

}

void AddJsonTools::setChatRoomList(QListWidget *chatRoomListTemp){
    this->chatRoomListTemp = chatRoomListTemp;
}

void AddJsonTools::changeJsonFile(qint32 desId, QString type, QString data, qint32 srcId, qint32 senderId, QString dirName) {
    QJsonObject newRecordObject;

    //(int)CONF.userId should be changed as infoHead->getScr()
    newRecordObject.insert("senderId",QJsonValue(senderId));
    newRecordObject.insert("type",QJsonValue(type));
    newRecordObject.insert("time",QJsonValue(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")));
    newRecordObject.insert("data",QJsonValue(QString("%1").arg(data)));

    qDebug() << "photo path:::" << QString("%1").arg(data);

    QByteArray byte;
    QFile historyFile((CONF.localDataPath + QString("Qtuber/%1").arg(desId) +  QString("/%1/%2.json").arg(dirName).arg(srcId)));
    qDebug() << "shishilujing ba :::" <<(CONF.localDataPath + QString("Qtuber/%1").arg(desId) + QString("/%1/%2.json").arg(dirName).arg(srcId));
    //write history
    if(historyFile.exists()){
        qDebug() << "existed";
        //TODO:
        historyFile.open(QIODevice::ReadWrite);
        byte = historyFile.readAll();
        historyFile.close();

        QJsonParseError json_error;
        QJsonDocument doc = QJsonDocument::fromJson(byte, &json_error);
        if(json_error.error == QJsonParseError::NoError){
                QJsonObject rootObj = doc.object();
                if(rootObj.contains("history") && rootObj.value("history").isArray()) {
                    QJsonArray newHistoryArray = rootObj.value("history").toArray();
                    newHistoryArray.append(newRecordObject);
                    rootObj["history"] = newHistoryArray;

                    // 构造新 json doc
                    QJsonDocument newDoc;
                    newDoc.setObject(rootObj);

                    QFile newHistory(CONF.localDataPath + QString("Qtuber/%1").arg(desId) + QString("/%1/%2.json").arg(dirName).arg(srcId));

                    if(newHistory.exists()){
                            newHistory.open(QIODevice::WriteOnly|QIODevice::Text);
                            doc.setObject(rootObj);
                            newHistory.seek(0);
                            newHistory.write(newDoc.toJson());
                            newHistory.flush();
                            newHistory.close();
                    }
                }
            }
    } else {
        bool ok=historyFile.open(QIODevice::WriteOnly);
        if(ok)
        {
            QJsonArray historyArrary;
            historyArrary.append(QJsonValue(newRecordObject));
            QJsonObject obj;
            obj.insert("history",QJsonValue(historyArrary));
            QJsonDocument doc(obj);
            QByteArray data=doc.toJson();

            historyFile.write(data);
            historyFile.close();
        }
        else
        {
            qDebug()<<"write error!"<<endl;
        }
    }

    if ( !historyFile.open( QIODevice::ReadWrite ) ) {
        qDebug() << "文件打开失败!\n";
        exit( 1 );
    }
    qDebug() << "文件打开成功";

    //read history
    this->chatRoomListTemp->clear();
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(historyFile.readAll(),&error);

    if(!doc.isNull() && error.error == QJsonParseError::NoError){
        QJsonObject jsonObject = doc.object();
        if ( jsonObject.contains( "history" ) && jsonObject.value( "history" ).isArray() ) {
             QJsonArray jsonArray = jsonObject.value( "history" ).toArray();
                for ( int i = 0; i < jsonArray.size(); i++ ) {
                    if ( jsonArray[ i ].isObject() ) {
                        QJsonObject jsonObjectPost = jsonArray[ i ].toObject();
                        if ( jsonObjectPost.contains( "senderId" ) &&
                             jsonObjectPost.contains( "type" ) &&
                             jsonObjectPost.contains( "time" ) &&
                             jsonObjectPost.contains( "data" )) {
                            if(jsonObjectPost["senderId"].toInt() == CONF.userId){
                                if(jsonObjectPost.value( "type" ).toString() == "text" ||
                                   jsonObjectPost.value( "type" ).toString() == "img" ||
                                   jsonObjectPost.value( "type" ).toString() == "file"){
                                    MyChatItem * myChatItem = new MyChatItem();
                                    QString avatorPath = CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/soloavator/%1.jpg").arg(CONF.userId);

                                    myChatItem->setAvator(avatorPath);
                                    myChatItem->setTime(jsonObjectPost.value( "time" ).toString());
                                    if(jsonObjectPost.value( "type" ).toString() == "text"){
                                        myChatItem->setMsg(jsonObjectPost.value( "data" ).toString());
                                    }
                                    else if(jsonObjectPost.value( "type" ).toString() == "img"){
                                        qDebug() << "test file path +++++++++++++++++++" << CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString();
                                        qDebug() << "asdsadsadsadas ::" << jsonObjectPost.value( "data" ).toString();
                                        myChatItem->addPic(CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString());
                                    }
        //                            TODO: 文件展示
                                    else if(jsonObjectPost.value( "type" ).toString() == "file"){
                                        myChatItem->setMsg("A file has be installed in: \n"+
                                                           CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/file/") + jsonObjectPost.value( "data" ).toString());
                                    }
                                    QListWidgetItem * listItem = new QListWidgetItem(this->chatRoomListTemp);
                                    listItem->setSizeHint(myChatItem->size());
                                    this->chatRoomListTemp->setItemWidget(listItem,myChatItem);
                                }

                                else if(jsonObjectPost.value("type").toString() == "voice"){
                                    VoiceMsg * voiceItem = new VoiceMsg(CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId)
                                                                    + QString("/soloavator/%1.jpg").arg(CONF.userId),
                                                                    jsonObjectPost.value( "time" ).toString(),
                                                                    CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId)
                                                                    + QString("/voice/") + jsonObjectPost.value( "data" ).toString());
                                    QListWidgetItem * listItem = new QListWidgetItem(this->chatRoomListTemp);
                                    listItem->setSizeHint(voiceItem->size());
                                    this->chatRoomListTemp->setItemWidget(listItem,voiceItem);
                                }

                            }
                            else{
                                ChatItem * chatItem = new ChatItem();
                                QString avatorPath = CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/soloavator/%1.jpg").arg(srcId);

                                chatItem->setAvator(avatorPath);
                                chatItem->setTime(jsonObjectPost.value( "time" ).toString());
                                if(jsonObjectPost.value( "type" ).toString() == "text"){
                                    chatItem->setMsg(jsonObjectPost.value( "data" ).toString());
                                }
                                else if(jsonObjectPost.value( "type" ).toString() == "img"){
                                    chatItem->addPic(CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/img/") + jsonObjectPost.value( "data" ).toString());
                                }
    //                            TODO: 文件展示
                                else if(jsonObjectPost.value( "type" ).toString() == "file"){
                                    chatItem->setMsg("A file has be installed in: \n"+
                                                       CONF.localDataPath + QString("Qtuber/%1").arg((int)CONF.userId) + QString("/file/") + jsonObjectPost.value( "data" ).toString());
                                }
                                QListWidgetItem * listItem = new QListWidgetItem(this->chatRoomListTemp);
                                listItem->setSizeHint(chatItem->size());
                                this->chatRoomListTemp->setItemWidget(listItem,chatItem);
                            }

                        }
                    }
               }
        }
    }
    this->chatRoomListTemp->setCurrentRow(this->chatRoomListTemp->count() - 1);
}
